<template>
  <!-- 图片展示模块 -->
  <div style="height: 100%">
    <div class="image-gallery">
      <div class="main-image-container" ref="imageContainer">
        <img
          v-if="currentImage && currentImage.url"
          :src="currentImage.url"
          :alt="currentImage.description"
          class="main-image"
          @touchstart="handleTouchStart"
          @touchmove="handleTouchMove"
          @touchend="handleTouchEnd"
          @wheel="handleWheel"
          @click="resetScale"
          :style="{ transform: `scale(${scale}) translate(${translateX}px, ${translateY}px)`, transition: 'transform 0.1s ease' }"
        />
      </div>
      <div>
        <button class="arrow left" @click="prevImage">&lt;</button>
        <button class="arrow right" @click="nextImage">&gt;</button>
        <div class="image-description" v-if="housingData">
          <div class="building-info">
            <div class="building-name">{{ housingData.housingName }}</div>
            <div class="building-intro">{{ housingData.remark || '' }}</div>
            <div class="building-intro">详细地址: {{ housingData.address }}</div>
            <div class="building-intro floor-selector">
              <span>总楼层数: {{ housingData.floor }}</span>
            </div>

            <div class="building-intro-container">
              <div class="building-intro">总面积: {{ housingData.totalArea?.toFixed(2) }}㎡</div>
              <div style="font-size: 14px; color: #89c0ee">
                <div v-if="!showFlag" @click="showFlag = true">展开租户详情</div>
                <div v-else @click="showFlag = false">收起租户详情</div>
              </div>
            </div>
            <div class="building-intro" style="color: #f68c53">空闲面积: {{ housingData.unreleasedArea?.toFixed(2) }}㎡</div>
            <div class="building-intro" style="color: #acc7fc">已出租面积: {{ housingData.leasedArea?.toFixed(2) }}㎡</div>

            <!-- 楼层信息弹窗触发器 -->
            <div class="floor-list" v-if="showFlag">
              <div v-for="(floor, index) in housingData.floors" :key="floor.id" class="floor-item">
                <div class="floor-header" @click="toggleFloorDetail(index)">
                  <h3>{{ floor.floorName }}</h3>
                  <img v-if="expandedFloorDetails.includes(index)" src="/src/assets/images/icon_up.png" alt="收起" class="floor-toggle-icon" />
                  <img v-else src="/src/assets/images/icon_down.png" class="floor-toggle-icon" />
                </div>
                <div v-show="expandedFloorDetails.includes(index)" class="floor-detail-content">
                  <div class="floor-info">
                    <p>本层面积: {{ floor.totalArea?.toFixed(2) }}㎡</p>
                    <p style="color: #f68c53">本层空闲面积: {{ floor.unreleasedArea?.toFixed(2) }}㎡</p>
                    <p style="color: #acc7fc">本层已出租面积: {{ floor.leasedArea?.toFixed(2) }}㎡</p>
                  </div>

                  <div class="enterprise-scroll-list">
                    <div class="enterprise-card" v-for="enterprise in floor.detailsDtoList" :key="enterprise.id">
                      <img :src="enterprise.logoUrl || qylogo" class="enterprise-logo" @error="(e) => (e.target.src = qylogo)" />
                      <div class="enterprise-info">
                        <h3 class="enterprise-name">{{ enterprise.enterpriseName }}</h3>
                        <p class="enterprise-intro">企业简介:{{ enterprise.enterpriseIntro }}</p>
                        <p class="enterprise-intro">入驻时间: {{ enterprise.leaseStart ? enterprise.leaseStart.split(' ')[0] : '' }}</p>
                        <p class="enterprise-intro">到期时间: {{ enterprise.leaseEnd ? enterprise.leaseEnd.split(' ')[0] : '' }}</p>
                      </div>
                    </div>
                  </div>
                  <!-- <div v-else class="no-enterprise">本楼层暂无入驻企业</div> -->
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 楼层详情弹窗 -->

        <!-- 入驻企业列表 -->

        <div class="thumbnail-container">
          <div v-for="(image, index) in images" :key="index" :class="['thumbnail', { active: index === currentIndex }]" @click="selectImage(index)">
            <img :src="image.url" :alt="housingData.files?.[index]?.remark || ''" />
            <div class="image-remark text-center">{{ housingData.files?.[index]?.remark || '' }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="Demo" lang="ts">
import { listDemo, getDemo, delDemo, addDemo, updateDemo } from '@/api/demo/demo';
import { DemoVO, DemoQuery, DemoForm } from '@/api/demo/demo/types';
import { getHouseingId, downloadImage, getHousingDetails } from '@/api/system/building';
import { useRoute } from 'vue-router';
import { getCurrentInstance, ref, onMounted, computed, reactive, watch } from 'vue';
import { ElSelect, ElOption, FormInstance } from 'element-plus';
import qylogo from '@/assets/images/qylogo.png';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const showFlag = ref(false);

interface Enterprise {
  id: number;
  logo: string;
  name: string;
  introduction: string;
  entryDate: string;
  leaseExpiration: string;
}

interface HousingData {
  floors?: number[];
  enterprises?: Record<number, Enterprise[]>;
  files?: Array<{ name: string; size: number; remark?: string }>;
  houseFloorDtoList?: Array<{ floor: number }>;
  id?: string | number;
}

const housingData = ref<HousingData>({ floors: [], enterprises: {}, files: [] });
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<FormInstance>();
const demoFormRef = ref<FormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: DemoForm = {
  id: undefined,
  deptId: undefined,
  userId: undefined,
  orderNum: undefined,
  testKey: undefined,
  value: undefined
};
const data = reactive<PageData<DemoForm, DemoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: undefined,
    userId: undefined,
    orderNum: undefined,
    testKey: undefined,
    value: undefined
  },
  rules: {
    id: [{ required: true, message: '主键不能为空', trigger: 'blur' }],
    deptId: [{ required: true, message: '部门id不能为空', trigger: 'blur' }],
    userId: [{ required: true, message: '用户id不能为空', trigger: 'blur' }],
    orderNum: [{ required: true, message: '排序号不能为空', trigger: 'blur' }],
    testKey: [{ required: true, message: 'key键不能为空', trigger: 'blur' }],
    value: [{ required: true, message: '值不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

// 图片数据
const images = ref([]);

// 当前图片索引
const currentIndex = ref(0);
const showFloorDialog = ref(false);
const currentFloor = ref(1);
const currentFloorEnterprises = ref([]);

const handleFloorChange = () => {
  // 实际项目中应根据currentFloor从API获取对应楼层企业数据
  currentFloorEnterprises.value = (housingData.value.enterprises || {})[currentFloor.value] || [];
};

// 初始化楼层数据
onMounted(() => {
  if (housingData.value.floors && housingData.value.floors.length > 0) {
    currentFloor.value = housingData.value.floors[0];
    handleFloorChange();
  }
});
const enterprises = ref([]);

// 计算属性：过滤当前楼层企业
const filteredEnterprises = ref([{}, {}]);

// 选择楼层
const selectFloor = (floorNum) => {
  currentFloor.value = floorNum;
  showFloorDialog.value = false;
};

// 计算属性：当前图片
const currentImage = computed(() => {
  return images.value[currentIndex.value];
});

// 上一张图片
const prevImage = () => {
  if (currentIndex.value > 0) {
    currentIndex.value--;
  } else {
    currentIndex.value = images.value.length - 1; // 循环到最后一张
  }
};

// 下一张图片
const nextImage = () => {
  if (currentIndex.value < images.value.length - 1) {
    currentIndex.value++;
  } else {
    currentIndex.value = 0; // 循环到第一张
  }
};

// 选择图片
const selectImage = (index: number) => {
  currentIndex.value = index;
};

const getHousingDetailsApi = async (housingId: any, floor: any, floorName: any) => {
  const data = await getHousingDetails({ housingId: housingId, floor: floor });
  if (data.code == 200) {
    //根据 赋值data.data中的数据到对应housingData.value.floors中id=floor的数据
    const floorData = housingData.value.floors.find((item) => item.id == floor);
    const floorIndex = housingData.value.floors.findIndex((item) => item.id == floor);

    if (floorData) {
      Object.assign(floorData, data.data);
    }
    for (let i = 0; i < data.data.detailsDtoList.length; i++) {
      console.log(data.data.detailsDtoList[i]);
      await loadImageForLogo(data.data.detailsDtoList[i]);
    }
    // 添加索引而不是ID，确保与模板中的判断条件匹配
    if (floorIndex !== -1) {
      expandedFloorDetails.value.push(floorIndex);
    }
    console.log('housingData.value.floors', housingData.value.floors);
  }
};

/** 查询测试单列表 */
const getList = async (housingId: any) => {
  loading.value = true;
  const res = await getHouseingId(housingId);
  if (res.code == 200) {
    housingData.value = res.data;
    images.value = [];
    for (let i = 0; i < housingData.value.files.length; i++) {
      await loadImageForFile(housingData.value.files[i]);
    }

    housingData.value.floors = [];
    housingData.value.floors = housingData.value.houseFloorDtoList;
    for (let i = 0; i < housingData.value.houseFloorDtoList.length; i++) {
      const floorItem = housingData.value.houseFloorDtoList[i];
      await getHousingDetailsApi(housingData.value.id, floorItem?.id as number, floorItem?.floorName as string);
    }
    // 获取企业列表数据
    enterprises.value = res.data.enterprises || [];
  }
  loading.value = false;
  //默认展开所有楼层
};

const loadImageForLogo = async (enterprises: any) => {
  if (enterprises.logoId) {
    try {
      // 发送POST请求获取图片流
      const response = await downloadImage(enterprises.logoId);
      // console.log('response', response);
      // 验证响应数据是否为blob格式
      if (response instanceof Blob) {
        // 将blob转换为Data URL
        const imageUrl = URL.createObjectURL(response);
        enterprises.logoUrl = imageUrl;

        console.log('images:', images.value);
      } else {
        console.error('响应不是blob格式:', response);
        // 备用URL
        // file.imageUrl = `http://localhost:8080/park/housing/downloadImage/${file.filePath}`;
      }
    } catch (error) {
      console.error('获取图片失败:', error);
      // 出错时返回备用URL
      // file.imageUrl = `http://localhost:8080/park/housing/downloadImage/${file.filePath}`;
    }
  }
};

const loadImageForFile = async (file: any) => {
  if (file.id) {
    try {
      // 发送POST请求获取图片流
      const response = await downloadImage(file.id);
      // console.log('response', response);
      // 验证响应数据是否为blob格式
      if (response instanceof Blob) {
        // 将blob转换为Data URL
        const imageUrl = URL.createObjectURL(response);
        images.value.push({
          url: imageUrl
        });
        console.log('images:', images.value);
      } else {
        console.error('响应不是blob格式:', response);
        // 备用URL
        // file.imageUrl = `http://localhost:8080/park/housing/downloadImage/${file.filePath}`;
      }
    } catch (error) {
      console.error('获取图片失败:', error);
      // 出错时返回备用URL
      // file.imageUrl = `http://localhost:8080/park/housing/downloadImage/${file.filePath}`;
    }
  }
};

onMounted(() => {
  console.log('11111');
  const route = useRoute();
  const housingId = route.query.id as string;
  if (housingId) {
    getList(housingId);
  }
});
const expandedFloors = ref<number[]>([]);

// 展开楼层详情的索引数组
const expandedFloorDetails = ref([]);

// 切换楼层详情展开/收起
const toggleFloorDetail = (index: number) => {
  const idx = expandedFloorDetails.value.indexOf(index);
  if (idx > -1) {
    expandedFloorDetails.value.splice(idx, 1);
  } else {
    expandedFloorDetails.value.push(index);
  }
};

// 获取指定楼层的企业列表
const getFloorEnterprises = (floorNum: number) => {
  return enterprises.value.filter((ent) => ent.floor === floorNum);
};

// 缩放相关状态
const scale = ref(1); // 缩放比例
const lastDistance = ref(0); // 上次触摸的距离
const startX = ref(0);
const startY = ref(0);
const translateX = ref(0);
const translateY = ref(0);
const isDragging = ref(false);
const imageContainer = ref(null);

// 最小和最大缩放比例
const MIN_SCALE = 1;
const MAX_SCALE = 5;

// 处理触摸开始事件
const handleTouchStart = (e) => {
  if (e.touches.length === 2) {
    // 双指操作 - 缩放
    const touch1 = e.touches[0];
    const touch2 = e.touches[1];
    lastDistance.value = Math.hypot(touch2.clientX - touch1.clientX, touch2.clientY - touch1.clientY);
  } else if (e.touches.length === 1 && scale.value > MIN_SCALE) {
    // 单指操作 - 拖动（仅在缩放后允许拖动）
    isDragging.value = true;
    startX.value = e.touches[0].clientX - translateX.value;
    startY.value = e.touches[0].clientY - translateY.value;
  }
};

// 处理触摸移动事件
const handleTouchMove = (e) => {
  if (e.touches.length === 2) {
    // 双指缩放
    const touch1 = e.touches[0];
    const touch2 = e.touches[1];
    const currentDistance = Math.hypot(touch2.clientX - touch1.clientX, touch2.clientY - touch1.clientY);

    if (lastDistance.value > 0) {
      const scaleFactor = currentDistance / lastDistance.value;
      const newScale = scale.value * scaleFactor;

      // 限制缩放范围
      scale.value = Math.max(MIN_SCALE, Math.min(MAX_SCALE, newScale));
    }

    lastDistance.value = currentDistance;
    e.preventDefault(); // 防止页面滚动
  } else if (e.touches.length === 1 && isDragging.value) {
    // 单指拖动
    translateX.value = e.touches[0].clientX - startX.value;
    translateY.value = e.touches[0].clientY - startY.value;
    e.preventDefault(); // 防止页面滚动
  }
};

// 处理触摸结束事件
const handleTouchEnd = () => {
  lastDistance.value = 0;
  isDragging.value = false;
};

// 处理鼠标滚轮事件（桌面端缩放）
const handleWheel = (e) => {
  e.preventDefault();

  // 计算缩放因子（正数为放大，负数为缩小）
  const scaleFactor = e.deltaY > 0 ? 0.9 : 1.1;
  const newScale = scale.value * scaleFactor;

  // 限制缩放范围
  scale.value = Math.max(MIN_SCALE, Math.min(MAX_SCALE, newScale));
};

// 重置缩放
const resetScale = () => {
  scale.value = 1;
  translateX.value = 0;
  translateY.value = 0;
};

// 重置缩放当切换图片时
const resetScaleOnImageChange = () => {
  resetScale();
};

// 监听图片切换，重置缩放状态
watch(currentIndex, () => {
  resetScale();
});
</script>

<style scoped>
/*左右布局*/
.building-intro-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.floor-selector :deep(.el-select) {
  background: transparent !important;
}

.floor-selector :deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.3) !important;
  box-shadow: none !important;
}

.floor-selector :deep(.el-input__inner) {
  background: transparent !important;
  border: none !important;
  color: white !important;
  font-size: 12px !important;
}

.floor-selector :deep(.el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.7) !important;
}

.floor-selector :deep(.el-select__popper) {
  background: rgba(0, 0, 0, 0.8) !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
  backdrop-filter: blur(10px);
}

.floor-selector :deep(.el-select-dropdown) {
  background: rgba(0, 0, 0, 0.8) !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
}

.floor-selector :deep(.el-select-dropdown__item) {
  color: white !important;
  font-size: 11px !important;
  padding: 4px 8px !important;
}

.floor-selector :deep(.el-select-dropdown__item:hover) {
  background: rgba(255, 255, 255, 0.1) !important;
}

.floor-selector :deep(.el-select-dropdown__item.selected) {
  background: rgba(64, 158, 255, 0.3) !important;
}

.floor-toggle {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 6px 8px;
  margin: 4px 0;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  cursor: pointer;
  font-size: 11px;
  transition: background-color 0.3s ease;
}

.floor-toggle:hover {
  background: rgba(255, 255, 255, 0.2);
}

.floor-toggle i {
  margin-left: 4px;
  transition: transform 0.3s ease;
}

.floor-list {
  overflow-y: auto;
  transition: max-height 0.3s ease;
  margin: 10px 0;
}

.floor-list.collapsed {
  max-height: 0;
  overflow: hidden;
}

.floor-switcher {
  margin: 16px 0;
}

.enterprise-scroll-list {
  /* max-height: 200px; */
  overflow-y: auto;
  padding: 0px;
}

.enterprise-card {
  display: flex;
  padding: 8px;
  margin-bottom: 8px;
  /* border: 1px solid #e5e7eb; */
  border-radius: 8px;
  align-items: center;
  font-size: 11px;
}

.enterprise-logo {
  width: 40px;
  height: 40px;
  object-fit: contain;
  margin-right: 8px;
}

.enterprise-info {
  flex: 1;
}

.enterprise-name {
  /* font-weight: bold; */
  margin-bottom: 2px;
  font-size: 14px;
}

.enterprise-intro {
  color: #fff;
  margin-bottom: 2px;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
  font-size: 14px;
}

.enterprise-dates {
  font-size: 10px;
  color: #999;
  display: flex;
  justify-content: space-between;
}

.floor-item {
  margin-bottom: 8px;
  padding: 4px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.floor-item h3 {
  margin: 4px 0;
  font-size: 13px;
}

.floor-info {
  font-size: 11px;
  margin-bottom: 4px;
}

.floor-info p {
  margin: 2px 0;
}

.image-gallery {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
}

.main-image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
}

.main-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.arrow {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  padding: 10px;
  cursor: pointer;
  z-index: 1;
}

.arrow.left {
  left: 10px;
}

.arrow.right {
  right: 10px;
}

.thumbnail-container {
  position: absolute;
  bottom: 20px;
  left: 50%;
  width: 70vw;
  max-width: 70%;
  height: 80px;
  transform: translateX(-50%);
  display: flex;
  justify-content: flex-start;
  gap: 10px;
  padding: 10px;
  flex-wrap: nowrap;
  margin-bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 8px;
  z-index: 10;
  overflow-x: auto;
  overflow-y: hidden;
  white-space: nowrap;
}

.thumbnail {
  width: 60px;
  height: 60px;
  border: 2px solid transparent;
  border-radius: 5px;
  overflow: hidden;
  cursor: pointer;
  transition: border-color 0.3s ease;
}

.thumbnail.active {
  border-color: #409eff;
}

.thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.image-description {
  position: absolute;
  top: 0;
  left: 20px;
  max-height: 100%;
  max-width: 300px;
  padding: 8px 12px;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.6) 100%);
  color: white;
  z-index: 10;
  overflow-y: auto;
  border-bottom-right-radius: 8px;
}
.building-info {
  font-size: 11px;
  height: 100%;
}
.building-name {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 2px;
}
.building-intro {
  margin: 1px 0;
  font-size: 14px;
}
.separator {
  color: rgba(255, 255, 255, 0.8);
}
.building-area {
  font-size: 14px;
  opacity: 0.9;
}

.floor-toggle-icon {
  width: 16px;
  height: 16px;
  vertical-align: middle;
  cursor: pointer;
}

.thumbnail {
  position: relative;
  display: inline-block;
  /* margin: 10px; */
  overflow: visible !important;
  width: 80px !important; /* 强制固定宽度 */
  flex-shrink: 0; /* 防止缩略图被压缩 */
}

.image-remark {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 0px;
  font-size: 14px;
  white-space: nowrap !important;
  overflow-x: hidden !important;
  overflow-y: hidden !important;
  box-sizing: border-box;
  -webkit-overflow-scrolling: touch;
}

.image-remark::-webkit-scrollbar {
  height: 6px;
}

.image-remark::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.5);
  border-radius: 3px;
}
.floor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 3px 5px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 3px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 3px;
}

.floor-header:hover {
  background: rgba(255, 255, 255, 0.2);
}

.floor-header h3 {
  margin: 0;
  font-size: 14px;
  color: #fff;
}

.floor-header i {
  font-size: 16px;
  color: #fff;
  transition: transform 0.3s ease;
}

.floor-detail-content {
  padding: 3px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 5px;
  margin-bottom: 5px;
}

.floor-info {
  margin-bottom: 10px;
}

.floor-info p {
  margin: 4px 0;
  font-size: 14px;
  color: #ddd;
}

.no-enterprise {
  text-align: center;
  color: #999;
  font-size: 14px;
  padding: 20px;
  font-style: italic;
}
</style>
